# 版本: 1.0.0
# 作者: 陈振玺
# 功能: CLI命令行界面，提供完整的邮件发送和配置管理功能

import click
import sys
from pathlib import Path
from typing import List, Optional
from rich.console import Console
from rich.table import Table
from rich.prompt import Prompt, Confirm
from rich.panel import Panel
from rich.text import Text

from .config import ConfigManager, EmailConfig, LLMConfig
from .email_sender import EmailSender
from .llm_client import LLMClient
from .utils import EmailContentProcessor, FileHandler

# 初始化控制台
console = Console()


@click.group()
@click.version_option(version="1.0.0", prog_name="smart-email")
def main():
    """Smart Email - 智能邮件发送工具
    
    支持终端发邮件、AI措辞优化、附件处理等功能。
    """
    pass


@main.group()
def config():
    """配置管理命令"""
    pass


@config.command("email")
@click.option('--smtp-server', help='SMTP服务器地址')
@click.option('--smtp-port', type=int, help='SMTP端口号')
@click.option('--username', help='用户名/邮箱地址')
@click.option('--password', help='密码')
@click.option('--use-tls/--no-tls', default=True, help='是否使用TLS')
@click.option('--use-ssl/--no-ssl', default=False, help='是否使用SSL')
def config_email(smtp_server, smtp_port, username, password, use_tls, use_ssl):
    """配置邮件设置"""
    try:
        config_manager = ConfigManager()
        
        # 如果没有提供参数，进入交互模式
        if not any([smtp_server, smtp_port, username, password]):
            console.print("[bold blue]配置邮件设置[/bold blue]")
            console.print()
            
            smtp_server = Prompt.ask("SMTP服务器地址", default="smtp.gmail.com")
            smtp_port = int(Prompt.ask("SMTP端口号", default="587"))
            username = Prompt.ask("用户名/邮箱地址")
            password = Prompt.ask("密码", password=True)
            use_tls = Confirm.ask("使用TLS加密", default=True)
            use_ssl = Confirm.ask("使用SSL加密", default=False)
        
        # 创建邮件配置
        email_config = EmailConfig(
            smtp_server=smtp_server,
            smtp_port=smtp_port or 587,
            username=username,
            password=password or "",
            use_tls=use_tls,
            use_ssl=use_ssl
        )
        
        # 测试连接
        console.print("[yellow]测试SMTP连接...[/yellow]")
        email_sender = EmailSender(email_config)
        test_result = email_sender.test_connection()
        
        if test_result['success']:
            # 保存配置
            config_manager.set_email_config(email_config)
            console.print("[green]✓ 邮件配置保存成功！[/green]")
        else:
            console.print(f"[red]✗ SMTP连接测试失败: {test_result['message']}[/red]")
            if not Confirm.ask("是否仍要保存配置", default=False):
                return
            config_manager.set_email_config(email_config)
            console.print("[yellow]邮件配置已保存（但连接测试失败）[/yellow]")
            
    except Exception as e:
        console.print(f"[red]配置邮件设置失败: {e}[/red]")
        sys.exit(1)


@config.command("llm")
@click.option('--api-url', help='LLM API URL')
@click.option('--api-key', help='API密钥')
@click.option('--model', help='模型名称')
@click.option('--max-tokens', type=int, help='最大token数')
@click.option('--temperature', type=float, help='温度参数')
def config_llm(api_url, api_key, model, max_tokens, temperature):
    """配置大语言模型设置"""
    try:
        config_manager = ConfigManager()
        
        # 如果没有提供参数，进入交互模式
        if not any([api_url, api_key, model]):
            console.print("[bold blue]配置大语言模型设置[/bold blue]")
            console.print()
            
            api_url = Prompt.ask("API URL", default="https://api.openai.com/v1")
            api_key = Prompt.ask("API密钥", password=True)
            model = Prompt.ask("模型名称", default="gpt-3.5-turbo")
            max_tokens = int(Prompt.ask("最大token数", default="1000"))
            temperature = float(Prompt.ask("温度参数 (0.0-2.0)", default="0.7"))
        
        # 创建LLM配置
        llm_config = LLMConfig(
            api_url=api_url or "https://api.openai.com/v1",
            api_key=api_key or "",
            model=model or "gpt-3.5-turbo",
            max_tokens=max_tokens or 1000,
            temperature=temperature or 0.7
        )
        
        # 测试连接
        console.print("[yellow]测试LLM API连接...[/yellow]")
        llm_client = LLMClient(llm_config)
        if llm_client.test_connection():
            # 保存配置
            config_manager.set_llm_config(llm_config)
            console.print("[green]✓ LLM配置保存成功！[/green]")
        else:
            console.print("[red]✗ LLM API连接测试失败[/red]")
            if not Confirm.ask("是否仍要保存配置", default=False):
                return
            config_manager.set_llm_config(llm_config)
            console.print("[yellow]LLM配置已保存（但连接测试失败）[/yellow]")
            
    except Exception as e:
        console.print(f"[red]配置LLM设置失败: {e}[/red]")
        sys.exit(1)


@config.command("show")
def config_show():
    """显示当前配置"""
    try:
        config_manager = ConfigManager()
        config_dict = config_manager.get_config_dict()
        
        console.print("[bold blue]当前配置信息[/bold blue]")
        console.print()
        
        # 显示邮件配置
        if config_dict.get('email'):
            email_table = Table(title="邮件配置")
            email_table.add_column("配置项", style="cyan")
            email_table.add_column("值", style="green")
            
            email_config = config_dict['email']
            email_table.add_row("SMTP服务器", email_config.get('smtp_server', 'N/A'))
            email_table.add_row("SMTP端口", str(email_config.get('smtp_port', 'N/A')))
            email_table.add_row("用户名", email_config.get('username', 'N/A'))
            email_table.add_row("密码", email_config.get('password', 'N/A'))
            email_table.add_row("使用TLS", str(email_config.get('use_tls', 'N/A')))
            email_table.add_row("使用SSL", str(email_config.get('use_ssl', 'N/A')))
            
            console.print(email_table)
            console.print()
        else:
            console.print("[yellow]邮件配置未设置[/yellow]")
            console.print()
        
        # 显示LLM配置
        if config_dict.get('llm'):
            llm_table = Table(title="LLM配置")
            llm_table.add_column("配置项", style="cyan")
            llm_table.add_column("值", style="green")
            
            llm_config = config_dict['llm']
            llm_table.add_row("API URL", llm_config.get('api_url', 'N/A'))
            llm_table.add_row("API密钥", llm_config.get('api_key', 'N/A'))
            llm_table.add_row("模型", llm_config.get('model', 'N/A'))
            llm_table.add_row("最大tokens", str(llm_config.get('max_tokens', 'N/A')))
            llm_table.add_row("温度", str(llm_config.get('temperature', 'N/A')))
            
            console.print(llm_table)
        else:
            console.print("[yellow]LLM配置未设置[/yellow]")
            
    except Exception as e:
        console.print(f"[red]显示配置失败: {e}[/red]")
        sys.exit(1)


@main.command()
@click.option('--to', required=True, help='收件人邮箱地址（可用逗号分隔多个）')
@click.option('--cc', help='抄送邮箱地址（可用逗号分隔多个）')
@click.option('--bcc', help='密送邮箱地址（可用逗号分隔多个）')
@click.option('--subject', required=True, help='邮件主题')
@click.option('--content', help='邮件内容')
@click.option('--content-file', type=click.Path(exists=True), help='邮件内容文件路径')
@click.option('--attachment', multiple=True, help='附件路径（可多次使用）')
@click.option('--optimize', is_flag=True, help='启用AI措辞优化')
@click.option('--tone', default='professional', 
              type=click.Choice(['professional', 'friendly', 'formal', 'casual']),
              help='邮件语调（仅在启用优化时有效）')
@click.option('--from-name', help='发件人显示名称')
@click.option('--content-type', default='plain',
              type=click.Choice(['plain', 'html']),
              help='邮件内容类型')
def send(to, cc, bcc, subject, content, content_file, attachment, optimize, tone, from_name, content_type):
    """发送邮件"""
    try:
        # 加载配置
        config_manager = ConfigManager()
        
        # 检查邮件配置
        email_config = config_manager.get_email_config()
        if not email_config:
            console.print("[red]邮件配置未设置，请先运行 'smart-email config email'[/red]")
            sys.exit(1)
        
        # 处理邮件内容
        content_processor = EmailContentProcessor()
        try:
            email_content = content_processor.process_content_input(content, content_file)
        except ValueError as e:
            console.print(f"[red]内容输入错误: {e}[/red]")
            sys.exit(1)
        
        # AI优化（如果启用）
        if optimize:
            llm_config = config_manager.get_llm_config()
            if not llm_config:
                console.print("[red]LLM配置未设置，无法启用AI优化。请先运行 'smart-email config llm'[/red]")
                if not Confirm.ask("是否继续发送（不优化）", default=True):
                    sys.exit(1)
            else:
                console.print("[yellow]正在优化邮件内容...[/yellow]")
                try:
                    llm_client = LLMClient(llm_config)
                    optimized_content = llm_client.optimize_email_content(
                        email_content, subject, "", tone
                    )
                    
                    # 显示优化结果
                    console.print("\n[bold blue]原始内容:[/bold blue]")
                    console.print(Panel(email_content, border_style="blue"))
                    
                    console.print("\n[bold green]优化后内容:[/bold green]")
                    console.print(Panel(optimized_content, border_style="green"))
                    
                    # 询问是否使用优化后的内容
                    if Confirm.ask("\n是否使用优化后的内容", default=True):
                        email_content = optimized_content
                        console.print("[green]已使用优化后的内容[/green]")
                    else:
                        console.print("[yellow]使用原始内容[/yellow]")
                        
                except Exception as e:
                    console.print(f"[red]内容优化失败: {e}[/red]")
                    if not Confirm.ask("是否继续发送（使用原始内容）", default=True):
                        sys.exit(1)
        
        # 格式化内容
        email_content = content_processor.format_email_content(email_content, content_type)
        
        # 验证附件
        file_handler = FileHandler()
        validated_attachments = []
        if attachment:
            for att_path in attachment:
                if file_handler.validate_file_path(att_path):
                    validated_attachments.append(Path(att_path))
                else:
                    console.print(f"[red]附件不存在或无效: {att_path}[/red]")
                    sys.exit(1)
        
        # 显示发送信息
        console.print("\n[bold blue]邮件发送信息:[/bold blue]")
        info_table = Table()
        info_table.add_column("项目", style="cyan")
        info_table.add_column("值", style="green")
        
        info_table.add_row("收件人", to)
        if cc:
            info_table.add_row("抄送", cc)
        if bcc:
            info_table.add_row("密送", bcc)
        info_table.add_row("主题", subject)
        if validated_attachments:
            att_names = [att.name for att in validated_attachments]
            info_table.add_row("附件", ", ".join(att_names))
        
        console.print(info_table)
        
        # 确认发送
        if not Confirm.ask("\n确认发送邮件", default=True):
            console.print("[yellow]邮件发送已取消[/yellow]")
            return
        
        # 发送邮件
        console.print("\n[yellow]正在发送邮件...[/yellow]")
        email_sender = EmailSender(email_config)
        
        result = email_sender.send_email(
            to_addresses=to,
            cc_addresses=cc,
            bcc_addresses=bcc,
            subject=subject,
            content=email_content,
            attachments=validated_attachments,
            content_type=content_type,
            from_name=from_name
        )
        
        if result['success']:
            console.print("[green]✓ 邮件发送成功！[/green]")
            
            # 显示发送详情
            if result.get('attachments'):
                console.print(f"\n附件信息:")
                for att in result['attachments']:
                    console.print(f"  - {att['name']} ({att['size']} bytes)")
        else:
            console.print(f"[red]✗ 邮件发送失败: {result['message']}[/red]")
            sys.exit(1)
            
    except Exception as e:
        console.print(f"[red]发送邮件时出错: {e}[/red]")
        sys.exit(1)


@main.command()
def test():
    """测试配置连接"""
    try:
        config_manager = ConfigManager()
        
        console.print("[bold blue]测试配置连接[/bold blue]")
        console.print()
        
        # 测试邮件配置
        email_config = config_manager.get_email_config()
        if email_config:
            console.print("[yellow]测试邮件配置...[/yellow]")
            email_sender = EmailSender(email_config)
            result = email_sender.test_connection()
            
            if result['success']:
                console.print("[green]✓ 邮件配置测试成功[/green]")
            else:
                console.print(f"[red]✗ 邮件配置测试失败: {result['message']}[/red]")
        else:
            console.print("[yellow]邮件配置未设置[/yellow]")
        
        console.print()
        
        # 测试LLM配置
        llm_config = config_manager.get_llm_config()
        if llm_config:
            console.print("[yellow]测试LLM配置...[/yellow]")
            llm_client = LLMClient(llm_config)
            
            if llm_client.test_connection():
                console.print("[green]✓ LLM配置测试成功[/green]")
            else:
                console.print("[red]✗ LLM配置测试失败[/red]")
        else:
            console.print("[yellow]LLM配置未设置[/yellow]")
            
    except Exception as e:
        console.print(f"[red]测试配置时出错: {e}[/red]")
        sys.exit(1)


if __name__ == '__main__':
    main()